from django import template

register = template.Library()

@register.filter
def split(value, arg):
    """将字符串按指定分隔符分割"""
    return value.split(arg)

@register.filter
def index(value, arg):
    """返回列表中指定索引的元素"""
    try:
        return value[int(arg)]
    except (IndexError, ValueError, TypeError):
        return ''

@register.filter
def multiply(value, arg):
    """将值乘以参数"""
    try:
        return float(value) * float(arg)
    except (ValueError, TypeError):
        return 0

@register.filter
def divide(value, arg):
    """将值除以参数"""
    try:
        return float(value) / float(arg)
    except (ValueError, TypeError, ZeroDivisionError):
        return 0

@register.filter
def option_labels(value):
    """将选项索引转换为选项标签 (0,1,2 -> A,B,C)"""
    if not value:
        return "未作答"

    labels = []
    option_map = {
        '0': 'A', '1': 'B', '2': 'C', '3': 'D',
        '4': 'E', '5': 'F', '6': 'G', '7': 'H',
        'A': 'A', 'B': 'B', 'C': 'C', 'D': 'D',
        'E': 'E', 'F': 'F', 'G': 'G', 'H': 'H'
    }

    # 处理多选题答案
    if isinstance(value, str):
        if ',' in value:
            indices = value.split(',')
        else:
            indices = list(value)  # 如果是连续的字符串（如"ABCD"），直接转换为列表

        for idx in indices:
            idx = idx.strip()
            if idx in option_map:
                labels.append(option_map[idx])
        return ', '.join(sorted(labels))  # 对选项进行排序
    # 处理单选题答案
    elif str(value) in option_map:
        return option_map[str(value)]
    else:
        return str(value)

@register.filter
def format_answer(answer, question_type):
    """格式化答案显示"""
    if not answer:
        return "未作答"

    if question_type == 'judge':
        if answer in ['T', '1', 'True', 'true', 'TRUE','正确']:
            return "正确"
        elif answer in ['F', '0', 'False', 'false', 'FALSE','错误']:
            return "错误"
        return answer

    # 处理选择题答案
    return option_labels(answer)